package com.example.zbh.dsliao.service;


import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.model.entity.LocalMusic;
import com.example.zbh.dsliao.model.entity.PersonalList;
import com.example.zbh.dsliao.utils.MyEventBus;
import com.example.zbh.dsliao.utils.FindSongs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class MyService extends Service {
    private static  final  String TAG = "MyService";
    private static int max;
    //定义一个播放对象
    private static MediaPlayer mediaPlayer;
    //我的歌曲列表
    private List<PersonalList> personalLists;
    private boolean isplay = false;
    private List<LocalMusic> localMusics;
    private String tag;//用于分辨本地歌曲和网络歌曲
    private String songUrl;
    private LocalMusic localMusic;
    private FindSongs finder;   //从手机里发现歌
    private int index = -1; //定义当前播放的歌曲位置
    private Handler handler = new Handler();




    Thread upProgress = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    if (mBindle.getMusicIsPlaying()) {
                        EventBus.getDefault().post(new MyEventBus.UpDataSeek(mediaPlayer.getCurrentPosition()));
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    });



    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(runnable, 500);
            //发送消息
            EventBus.getDefault().post(new MyEventBus.UpDataSeek(mediaPlayer.getCurrentPosition()));
            /*mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    try {
                        Log.d("what", "自动下一首");
                        mBindle.next();
                    *//*handler.postDelayed(runnable, 500);*//*
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });*/
        }
    };

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mBindle;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        handler.postDelayed(runnable, 500);
        //注册
        EventBus.getDefault().register(this);
        //初始化音频对象
        mediaPlayer = new MediaPlayer();
        //初始化finder
        finder = new FindSongs();
        localMusics = finder.getMp3Infos(MyService.this.getContentResolver());
        Log.i("what", "mp3Infos----1" + localMusics);
        Log.i("what", "->service onCreate");
//        upProgress.start();

        /**
         * 播放完成的监听
         */
        /*mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                try {
                    mBindle.next();
                    Log.d("what", "setOnPreparedListener:自动下一首");
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });*/
    }

    /***
     * onEvent
     */
    public void onEvent(MyEventBus.ActivityCreate activityCreate) {
        EventBus.getDefault().post(new MyEventBus.SeekBarMax(mediaPlayer.getDuration()));
        Log.i("what", "post->" + mediaPlayer.getDuration());

    }

    public void onEvent(MyEventBus.MusicDatas musicDatas) {
        this.localMusics = musicDatas.getDatas();
        Log.i("what", "mp3Infos----2:" + localMusics);
    }

    public void onEvent(MyEventBus.CurrentIndex index) {
        this.index = index.getCurrentIndex();
        Log.i("what", "index___eventbus:" + index);
    }

    /**
     * 实现idle接口
     */
    MusicIdle.Stub mBindle = new MusicIdle.Stub() {
        /**
         * 设置url
         * @param url
         * @throws RemoteException
         */
        @Override
        public void setUrl(String url) throws RemoteException {
            Log.i("what", "url-get" + url);
            try {
                mediaPlayer.reset();
                mediaPlayer.setOnPreparedListener(null);
                mediaPlayer.setDataSource(url);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置音频流
                mediaPlayer.prepare();//储存卡内容加载或者网络中的部分媒体内容加载到内存中
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * 设置当前进度
         */
        @Override
        public int setCurrentIndex() throws RemoteException {
            return mediaPlayer.getCurrentPosition();
        }

        /**
         * 获取
         */
        @Override
        public void setProgress(int progress) throws RemoteException {
            mediaPlayer.seekTo(progress);
        }

        /**
         * 获得音频时长
         */
        @Override
        public int getDuration() throws RemoteException {
            return mediaPlayer.getDuration();
        }

        /**
         * 下一首
         */
        @Override
        public void next() throws RemoteException {
            if (index + 1 > localMusics.size() - 1) {
                index = 0;
            } else {
                index++;
            }
            songUrl = localMusics.get(index).getUrl();
            Log.i("what", "songUrl" + songUrl);
            EventBus.getDefault().post(new MyEventBus.SingerName(localMusics.get(index).getArtist()));
            EventBus.getDefault().post(new MyEventBus.SongsName(localMusics.get(index).getTitle()));
            setUrl(songUrl);
            mediaPlayer.start();
        }

        /**
         * 上一首
         */
        @Override
        public void previous() throws RemoteException {
            if (index == 0) {
                index = localMusics.size() - 1;
            } else {
                index--;
            }
            songUrl = localMusics.get(index).getUrl();
            Log.i("what", "songUrl" + songUrl);
            EventBus.getDefault().post(new MyEventBus.SingerName(localMusics.get(index).getArtist()));
            Log.i("what", "service---singer" + localMusics.get(index).getArtist());
            EventBus.getDefault().post(new MyEventBus.SongsName(localMusics.get(index).getTitle()));
            setUrl(songUrl);
            mediaPlayer.start();
        }

        @Override
        public String datas() throws RemoteException {
            Log.i("what", "0-------");
            return localMusics.get(index).getArtist();
        }



        /**
         * 播放
         */
        @Override
        public void play() throws RemoteException {
            Log.d("TestService", "start");
            mediaPlayer.start();
        }

        /**
         * 暂停
         */
        @Override
        public void pause() throws RemoteException {
            Log.d("TestService", "pause");
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }
        }

        /**
         * 停止
         */
        @Override
        public void stop() throws RemoteException {
            mediaPlayer.stop();
        }

        /**
         * 是否正在播放
         */
        @Override
        public boolean getMusicIsPlaying() throws RemoteException {
            return mediaPlayer.isPlaying();
        }

    };


    public static int getMax() {
        return mediaPlayer.getDuration();
    }

    public static int getProgress() {
        return mediaPlayer.getCurrentPosition();
    }





    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }

        mediaPlayer.release();
        mediaPlayer = null;

        EventBus.getDefault().unregister(this);
    }
}